#include "sessionfriendarea.h"

#include <QScrollBar>
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QStyleOption>
#include <QPainter>

#include "debug.h"
#include "mainwidget.h"
#include "model/data.h"

//////////////////////////////////////
/// 会话列表中的好友区域
//////////////////////////////////////

SessionFriendArea::SessionFriendArea(QWidget *parent)
    : QScrollArea{parent}
{
    // 1.设置必要的属性
    this->setWidgetResizable(true); // 必须设置这个属性才能实现滚动
    this->verticalScrollBar()->setStyleSheet("QScrollBar:vertical { width:2px; "
                                             "background-color:rgb(26, 26, 26);}");
    this->horizontalScrollBar()->setStyleSheet("QScrollBar:horizontal { height:0px; }");
    this->setFrameStyle(QFrame::NoFrame);

    // 2.创建 Widget
    container = new QWidget();
    container->setFixedWidth(250);
    this->setWidget(container);

    // 3.给 Widget 添加布局管理器
    QVBoxLayout* layout = new QVBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setAlignment(Qt::AlignTop);

    container->setLayout(layout);

#if TEST_F
    // 测试
    for(int i = 1;i <= 30;i ++) {
        QIcon icon(":/resource/image/default_avatar.png");
        this->addItem(SessionType, QString::number(i), icon,
                      "lufei-" + QString::number(i), "msg-" + QString::number(i));
    }
#endif
}

void SessionFriendArea::addItem(ItemType type, const QString& id, const QIcon &avatar,
                                const QString &name, const QString &text)
{
    SessionFriendItem* item = nullptr;
    if(type == SessionType) {
        item = new SessionItem(id, this, avatar, name, text);
    } else if(type == FriendType) {
        item = new FriendItem(id, this, avatar, name, text);
    } else if(type == ApplyType) {
        item = new ApplyItem(id, this, avatar, name);
    } else {
        LOG() << "未知的 ItemType: " << type;
        return;
    }
    container->layout()->addWidget(item);
}

void SessionFriendArea::clear()
{
    QLayout* layout = container->layout();
    for(int i = layout->count() - 1; i >= 0;i --) {
        QLayoutItem* item = layout->takeAt(i);
        if(item != nullptr && item->widget() != nullptr) {
            delete item->widget();
        }
        delete item;
    }
}

void SessionFriendArea::clickItem(int index)
{
    if(index < 0 || index >= container->layout()->count()) {
        LOG() << "非法的下标: " << index;
        return;
    }
    QLayoutItem* layoutItem = container->layout()->itemAt(index);
    if(layoutItem == nullptr || layoutItem->widget() == nullptr) {
        LOG() << "指定元素不存在";
        return;
    }
    SessionFriendItem* item = dynamic_cast<SessionFriendItem*>(layoutItem->widget());
    item->select();
}

//////////////////////////////////////
/// 滚动区域中的 item
//////////////////////////////////////

SessionFriendItem::SessionFriendItem(QWidget *owner, const QIcon &avatar,
                                     const QString &name, const QString &text)
    :owner(owner)
{
    // 设置 Item 属性
    this->setFixedHeight(70);
    this->setStyleSheet("QWidget { background-color:rgb(230, 230, 230)}");

    // 设置布局管理器
    QGridLayout* layout = new QGridLayout();
    layout->setHorizontalSpacing(10);
    layout->setVerticalSpacing(0);
    layout->setContentsMargins(10, 0, 0, 0);
    layout->setAlignment(Qt::AlignLeft);
    this->setLayout(layout);

    // 头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(50, 50);
    avatarBtn->setIcon(avatar);
    avatarBtn->setIconSize(QSize(50, 50));

    // 名字
    QLabel* nameLabel = new QLabel(name);
    nameLabel->setStyleSheet("QLabel { font-size:18px; "
                             "font-weight:600; }");
    nameLabel->setFixedHeight(35);

    // 最近一条消息
    msgLabel = new QLabel(text);
    msgLabel->setStyleSheet("QLabel { font-size:10px; }");
    msgLabel->setFixedHeight(35);

    // 添加到布局管理器
    layout->addWidget(avatarBtn, 0, 0, 2, 1);
    layout->addWidget(nameLabel, 0, 1, 1, 2);
    layout->addWidget(msgLabel, 1, 1, 1, 1);
}

void SessionFriendItem::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

void SessionFriendItem::mousePressEvent(QMouseEvent *event)
{
    this->select();
}

void SessionFriendItem::enterEvent(QEnterEvent *event)
{
    this->setStyleSheet("QWidget { background-color: rgb(200, 200, 200); }");
}

void SessionFriendItem::leaveEvent(QEvent *event)
{
    if(this->selected == true) {
        return;
    }
    this->setStyleSheet("QWidget { background-color: rgb(230, 230, 230); }");
}

void SessionFriendItem::select()
{
    // 将其他 Item 背景还原
    const QObjectList &children = this->parentWidget()->children();
    for(auto &e : children) {
        if(!e->isWidgetType()) {
            continue;
        }
        // dynamic_cast: 将父类指针/引用转换成子类指针/引用
        SessionFriendItem* item = dynamic_cast<SessionFriendItem*>(e);
        if(item->selected == true) {
            item->selected = false;
            item->setStyleSheet("QWidget { background-color: rgb(230, 230, 230); }");
        }
    }

    this->selected = true;
    this->setStyleSheet("QWidget { background-color: rgb(200, 200, 200); }");

    // 点击当前 item 处理对应的业务
    this->active();
}

void SessionFriendItem::active() {}

//////////////////////////////////////
/// 会话 item
//////////////////////////////////////

SessionItem::SessionItem(const QString &sessionId, QWidget *owner,
                         const QIcon &avatar, const QString &name, const QString &msg)
    :SessionFriendItem(owner, avatar, name, msg), sessionId(sessionId), text(msg)
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    connect(dataCenter, &model::DataCenter::addSelfMessageDone, this, &SessionItem::updateLastMessage);

    // load unread message count
    int count = dataCenter->getUnreadMsgCount(sessionId);
    if(count > 0) {
        msgLabel->setText(QString("[unread %1 ]").arg(count) + text);
    }
}

void SessionItem::active()
{
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->loadRecentMessage(sessionId);

    // clear unread message count
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->clearUnreadMsgCount(sessionId);
    msgLabel->setText(text);
}

void SessionItem::updateLastMessage(const QString &chatSessionId)
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    if(chatSessionId != sessionId) {
        return;
    }
    // 1.get last message
    QList<Message>* list = dataCenter->getRecentMessageList(chatSessionId);
    if(list == nullptr || list->size() == 0) {
        return;
    }
    Message msg = list->back();
    // 2.update
    if(msg.type == model::TEXT_TYPE) {
        text = msg.content;
    } else if(msg.type == model::FILE_TYPE) {
        text = "[file]";
    } else if(msg.type == model::IMAGE_TYPE) {
        text = "[image]";
    } else if(msg.type == model::SPEECH_TYPE) {
        text = "[speech]";
    }

    if(chatSessionId == dataCenter->getCurrentSessionId()) {
        msgLabel->setText(text);
    } else {
        int count = dataCenter->getUnreadMsgCount(sessionId);
        if(count > 0) {
            msgLabel->setText(QString("[unread %1 ]").arg(count) + text);
        }
    }
}

//////////////////////////////////////
/// 好友 item
//////////////////////////////////////

FriendItem::FriendItem(const QString &userId, QWidget *owner,
                       const QIcon &avatar, const QString &name, const QString &msg)
    :SessionFriendItem(owner, avatar, name, msg), userId(userId)
{

}

void FriendItem::active()
{
    MainWidget* mainWidget = MainWidget::getInstance();
    mainWidget->switchToSession(this->userId);
}

//////////////////////////////////////
/// 申请 item
//////////////////////////////////////

ApplyItem::ApplyItem(const QString &userId, QWidget *owner,
                     const QIcon &avatar, const QString &name)
    :SessionFriendItem(owner, avatar, name, ""), userId(userId)
{
    // 1.将 msgLabel 移除
    QLayout* layout = this->layout();
    QGridLayout* gridLayout = dynamic_cast<QGridLayout*>(layout);
    QLayoutItem* item = gridLayout->itemAtPosition(1, 1);
    QWidget* widget = item->widget();
    QLabel* msgLabel = dynamic_cast<QLabel*>(widget);
    gridLayout->removeWidget(msgLabel);
    delete msgLabel;

    // 2.添加 同意 拒绝 按钮
    QPushButton* acceptBtn = new QPushButton();
    acceptBtn->setIcon(QIcon(":/resource/image/accept.png"));
    acceptBtn->setIconSize(QSize(25, 25));
    QString style1 = "QPushButton { border:none; }";
    style1 += "QPushButton:hover { background-color:rgb(150,150,150); }";
    acceptBtn->setStyleSheet(style1);

    QPushButton* rejectBtn = new QPushButton();
    rejectBtn->setIcon(QIcon(":/resource/image/reject.png"));
    rejectBtn->setIconSize(QSize(25, 25));
    QString style2 = "QPushButton { border:none; }";
    style2 += "QPushButton:hover { background-color:rgb(150,150,150); }";
    rejectBtn->setStyleSheet(style2);

    // 3.添加到布局管理器中
    gridLayout->addWidget(acceptBtn, 1, 1, 1, 1);
    gridLayout->addWidget(rejectBtn, 1, 2, 1, 1);

    connect(acceptBtn, &QPushButton::clicked, this, &ApplyItem::acceptFriendApply);
    connect(rejectBtn, &QPushButton::clicked, this, &ApplyItem::rejectFriendApply);
}

void ApplyItem::active()
{
}

void ApplyItem::acceptFriendApply()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->acceptFriendApplyAsync(this->userId);
}

void ApplyItem::rejectFriendApply()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    dataCenter->rejectFriendApplyAsync(this->userId);
}
